package eva.savant.core.view

import eva.savant.businessobject.gl.Sociedad
import eva.savant.businessobject.ad.Sistema
import eva.savant.businessobject.ad.Usuario
import eva.savant.core.service.EntityService
import eva.savant.core.service.ReportService
import eva.savant.core.view.util.FacesUtils
import eva.savant.core.service.NameService
import eva.savant.businessobject.Entity

import javax.faces.convert.Converter
import javax.faces.context.FacesContext
import javax.faces.component.UIComponent
import javax.sql.DataSource
import java.lang.reflect.Field

public class Base implements Serializable {

  public static final Integer BAJA = 0;

  public static final Integer ALTA = 1;


  public Object getEntity(String queryService, final Object... values) {

    return entityService.getEntity(queryService,values)
  }

  public List getLsEntity(String queryService, final Object... values) {

    return entityService.getLsEntity(queryService,values)
  }

  public static <T> T get(Class <T> tClass, Object primaryKey) {

    return entityService.find(tClass, primaryKey)
  }

  public static <T> T get(Class <T> tClass, Object... values) {

    def model= find(tClass, values)

    return model != null && model.size() > 0? model[0] : null
  }

    public static <T> List<T> find(Class<T> tClass, Object... values) {

        def selectWhere= (String) values[0]

        values[0]= sociedad.id

        def miWhere= selectWhere.split(':')



        def select= 'm'

        if(miWhere.length > 1) {

          select= ''

          def lsCol= miWhere[0].split(',')

          for(col in lsCol) {

            col= col.trim()

            def aux= col.split('\\(')

            select= select + (aux.length > 1? col.replace('(','(m.') : 'm.' + col) + ', '
          }

          select= select.substring(0,select.length()-2)
        }


        def where= miWhere.length > 1? miWhere[1] : selectWhere

        where= where.replaceAll('^\\s+|\\s+$',''); //println 'dsalida-'+where+'-'

        def aux= where.split(' ')

        def wheres= ''

        for(dat in aux) wheres= wheres + ( dat.indexOf('.') > 0? 'm.'+dat : dat ) + ' '


        wheres= wheres.trim()
        //println 'wheres: '+wheres

        def cont= 2, res= ''

        char car= '?'


        for(int i = 0; i < wheres.length(); i++) {

            def c= wheres.charAt(i); res =  res + c

            if(c==car) { res =  res + cont;  cont++ }
        }
                                      // println 'res:-'+res+'-'

        res= 'm.sociedadId=?1 and m.operacionId > 0' + ((res.length()> 0)? ' and ' : '') + res


        res= res.replace('and order','order')


        def queryString = 'select '+select+' from ' + tClass.canonicalName + ' m where ' + res



        println queryString + '\n ' +values

        return miWhere.length > 1? entityService.find(queryString,values) : entityService.find(tClass,queryString,values)
    }

    public static <T> List<T> completeLike(Class<T> tClass, String field, String value) {

      return find(tClass, field + ' like ?','%' + value.replaceAll('\\*','%')+'%')
    }

    public static Converter converterLike(Class tClass) { return new Converter() {

      public Object getAsObject(FacesContext context, UIComponent component, String value) {

      if(value == null || value.trim().equals('') || value.trim().equals('null')) return null


      def type= Field.getTypeName(tClass.getDeclaredField('id').type)

      def code= type.equals('java.lang.Integer')? new Integer(value) : value


      return get(tClass, code) }


      public String getAsString(FacesContext context, UIComponent component, Object value) {

      return value == null? '' : value.id + '' }

    }; }

  public void persist(Object entity) {

    entityService.persist(entity)
  }

  public <T> T merge(T entity) {

    return entityService.merge(entity)
  }

  public void delete(Object entity) {

    entityService.delete(entity)
  }

  public <T> T remove(T entity) {

    return entityService.remove(entity)
  }

  public Sistema getSistema() {

    return FacesUtils.coreBean.sistema
  }

  public Usuario getUsuario() {

    return FacesUtils.coreBean.usuario
  }

  public static Sociedad getSociedad() {

    return FacesUtils.coreBean.sociedad
  }

  public TimeZone getTimeZone() {

    return TimeZone.default
  }

  public static void addInfoMessage(String msg) {

    FacesUtils.addInfoMessage msg
  }

  public static void addErrorMessage(String msg) {

    FacesUtils.addErrorMessage msg
  }

  public static void addErrorMessage(Exception e) {

    FacesUtils.addErrorMessage e
  }

  public static Object getManagedBean(String name) {

    return FacesUtils.getManagedBean(name)
  }

  public static Object getSpringBean(String name) {

    return FacesUtils.getSpringBean(name)
  }

  public static DataSource toDataBase() {

    return (DataSource) FacesUtils.getSpringBean(NameService.DB_SERVICE)
  }

  public static EntityService getEntityService() {

    return (EntityService) getSpringBean(NameService.ENTITY_SERVICE)
  }

  public static ReportService getReportService() {

    return (ReportService) getSpringBean(NameService.SERVICE_REPORT)
  }

  public Entity alta(Object entity) {

    entity= (Entity) entity

    entity.sociedadId= sociedad.id

    entity.operacionId= ALTA

    entity.usuarioId= usuario.id

    return entity
  }

}
